package io.github.consoles.dsa;

import java.util.Iterator;

/**
 * Created by yiihua-013 on 17/1/22.
 * <p>
 * 链表实现队列
 */
public class LinkedQueue<Item> implements Iterable<Item> {

    private class Node {
        Item item;
        Node next;
    }

    private Node first; // 队头
    private Node last; // 队尾
    private int size;

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return size;
    }

    /**
     * 入队列
     * 表尾追加
     *
     * @param item
     */
    public void enqueue(Item item) {
        Node oldLast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else oldLast.next = last;
        size++;
    }

    /**
     * 出队列
     * 表头删除
     *
     * @return
     */
    public Item dequeue() {
        Item item = first.item;
        first = first.next;
        size--;
        if (isEmpty()) last = null;
        return item;
    }

    private class LinkedIterator implements Iterator<Item> {

        private Node current = first;

        /**
         * 每次调用next,current指针将会变化,从而导致hasNext变化
         *
         * @return
         */
        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

    @Override
    public Iterator<Item> iterator() {
        return new LinkedIterator();
    }

    /**
     * 连接2个队列
     *
     * @param queue
     * @return
     */
    public LinkedQueue<Item> catenation(LinkedQueue<Item> queue) {
        last.next = queue.first;
        last = queue.last;
        size += queue.size;
        queue = null; // 值传递?
        return this;
    }
}
